package com.quanyan.travel.exception.handler;

import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.travel.component.asyn.TravelAsyncService;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 *
 * travel 全局异常捕获,控制器增强,适用于所有使用@ RequestMapping
 * @author songzj
 * @date 16/4/15-11:01
 */
@ControllerAdvice
public class TravelExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(TravelExceptionHandler.class);

    @Autowired
    private TravelAsyncService travelAsyncService;


    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseEntity<?> exceptionHandler(HttpServletRequest request, Exception e) {
        String errorMsg = ExceptionUtils.getStackTrace(e);
        travelAsyncService.sendMail(request, errorMsg);
        logger.error("exceptionHandler: stacktrace={}", errorMsg);
        return new ResponseEntity(APIResponse.returnFail(ApiResponseEnum.INTERNAL_ERROR), HttpStatus.INTERNAL_SERVER_ERROR);
    }


}
